<template>
  <!-- 头部导航栏 -->
  <view class="navbar" :style="{ paddingTop: menu?.top + 'px' }">
    <image src="http://xcxtp.njmswl.com/images/goBack.png" class="goBack" @tap="goBack" />
    <text class="title">租房</text>
  </view>
  <view class="search">
    <image  @click="searchBtn"  src="http://xcxtp.njmswl.com/images/search.png" class="searchImg" />
    <input v-model="pageParams.name" @change="searchBtn"  type="text"  class="input" placeholder="请输入小区/商圈" />
  </view>
  <view class="screen">
    <view class="screenItem">
      <text class="screen-text">区域</text>
      <image src="http://xcxtp.njmswl.com/images/market.png" class="market" />
    </view>
    <view class="screenItem">
      <text class="screen-text">租金</text>
      <image src="http://xcxtp.njmswl.com/images/market.png" class="market" />
    </view>
    <view class="screenItem">
      <text class="screen-text">房型</text>
      <image src="http://xcxtp.njmswl.com/images/market.png" class="market" />
    </view>
    <view class="screenItem" @tap="switchImage">
      <text class="screen-text">更多</text>
      <image
        :src="
          isMoreSelected
            ? 'http://xcxtp.njmswl.com/images/up.png'
            : 'http://xcxtp.njmswl.com/images/market.png'
        "
        class="market"
      />
    </view>
  </view>
  <scroll-view
    class="scroll-view"
    @scrolltolower="onScrolltolower"
    @refresherrefresh="OnRefresherRefresh"
    refresher-enabled="true"
    :refresher-triggered="isTriggered"
    scroll-y
  >
    <view v-if="isMoreSelected" class="bg">
      <view class="moreType" v-for="(category, index) in categories" :key="index">
        <view class="moreType-title">{{ category.title }}</view>
        <view class="moreTypeConten">
          <view
            class="contentTag"
            v-for="(option, optIndex) in category.options"
            :key="`${index}-${optIndex}`"
          >
            {{ option }}
          </view>
        </view>
      </view>
      <!-- ../../static/images/reset.png -->
      <view class="bottom-container">
        <view class="left-reset">
          <image src="http://xcxtp.njmswl.com/images/reset.png" class="resetImg" />
          <view class="resetText">重置</view>
        </view>
        <view class="confirm"> 确认 </view>
      </view>
    </view>
    <view v-else>
      <view
        v-if="!isAccessTokenSet"
        class="content"
        v-for="item in list"
        :key="item.id"
        @click="detail(item.id)"
      >
        <button
          open-type="getPhoneNumber"
          @getphonenumber="onGetphonenumber"
          style="height: 230rpx"
        >
          <view class="contentItem">
            <image
              :src="item.images && item.images.length ? item.images[0] : defaultImage"
              class="contentItemImg"
            />
            <view class="description">
              <p class="desTitle">{{ item.leaseType }}·{{ item.name }}·{{ item.type }}</p>
              <p class="positionContent">
                <span class="houseTag">{{ item.area }}㎡</span>
                <span class="houseTag">{{ item.asaga }}</span>
                <span class="houseTag">{{ item.location }}</span>
                <span class="houseTag"></span>
              </p>
              <p class="priceContent">
                <span class="allPrice">{{ item.price }}元/月</span>
              </p>
              <p class="tagContent">
                <span class="houseLabel" v-for="(item, index) in item.tags" :key="index">{{
                  item
                }}</span>
              </p>
            </view>
          </view>
        </button>
      </view>
      <view v-else class="content" v-for="item in list" :key="item.id" @click="goDetail(item.id)">
        <view class="contentItem">
          <image
            :src="item.images && item.images.length ? item.images[0] : defaultImage"
            class="contentItemImg"
          />
          <view>
            <p class="desTitle">{{ item.leaseType }}·{{ item.name }}·{{ item.type }}</p>
            <p>
              <span class="houseTag">{{ item.area }}㎡</span>
              <span class="houseTag">{{ item.asaga }}</span>
              <span class="houseTag">{{ item.location }}</span>
              <span class="houseTag"></span>
            </p>
            <p>
              <span class="allPrice">{{ item.price }}元/月</span>
            </p>
            <p>
              <span class="houseLabel" v-for="(item, index) in item.tags" :key="index">{{
                item
              }}</span>
            </p>
          </view>
        </view>
      </view>
      <open-program></open-program>
    </view>
  </scroll-view>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import OpenProgram from '../components/openProgram.vue'
import { computed } from 'vue'
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { getLoginAPI, getSocialLoginAPI } from '@/services/login'
import {
  getRentHouseAPI,
  getRentHousePageAPI,
  getRentHouseCollectionCreateAPI,
} from '@/services/rentHouse'
const menu = ref({})

//下拉刷新-------------------------------------------------------------------------------------
const isTriggered = ref(false)
const OnRefresherRefresh = async () => {
  isTriggered.value = true
  await Promise.all([refreshRentHousePageList()])
  isTriggered.value = false
}
//---------------------------------------------------------------
// const label = ref(["配套成熟", "满五", "大户型"]);
const tag = ref(['中海国际一期', '115㎡', '3室2厅1卫', '南'])
const isMoreSelected = ref(false)
const categories = ref([
  {
    title: '户型面积',
    options: [
      '50㎡以下',
      '50-70㎡',
      '70-90㎡',
      '90-110㎡',
      '110-130㎡',
      '130-150㎡',
      '150-200㎡',
      '2000㎡以上',
    ],
  },
  {
    title: '物业类型',
    options: ['住宅', '别墅', '写字楼', '商铺', '商业'],
  },
  {
    title: '楼盘特色',
    options: [
      '小户型',
      '低总价',
      '在售',
      '地铁沿线',
      '降价',
      '刚需优选',
      '公交直达',
      '最新开盘',
      '住宅',
    ],
  },
  {
    title: '销售状态',
    options: ['待售', '在售', '售罄'],
  },
  {
    title: '开盘时间',
    options: ['本月开盘', '未来一个月', '未来三个月', '未来半年', '过去一个月', '过去三个月'],
  },
])
const detailId = ref()
const detail = (id) => {
  detailId.value = id
}
const goDetail = (id) => {
  uni.navigateTo({
    url: `/pages/simplePage/rentHouseDetail?id=${id}`, // 假设detail页面需要id参数
  })
}
onMounted(() => {
  // console.log(menu.value);
})

const goBack = () => {
  uni.switchTab({
    url: '/pages/index/index', // 这里的url是你首页的路径，根据你的项目实际情况进行修改
  })
}

const switchImage = () => {
  isMoreSelected.value = !isMoreSelected.value
}
//租房数据请求
const getRentHouseList = async () => {
  const res = await getRentHouseAPI({
    id: 1024,
  })
}

//租房分页数据请求
//1.分页参数
const pageParams = {
  pageNo: 1,
  pageSize: 5,
  name:''
}
//2. 分页已结束标记
const finish = ref(false)
//3.列表数据
const list = ref([])

// 获取租房分页数据列表
const getRentHousePageList = async () => {
  // 数据加载完，退出继续追加分页数据
  if (finish.value === true) {
    return uni.showToast({
      icon: 'none',
      title: '没有更多数据了~',
    })
  }
  const res = await getRentHousePageAPI(pageParams)
  if (res.code == 0) {
    list.value.push(...res.data.list)
  }
  if (pageParams.pageNo < res.data.total / pageParams.pageSize) {
    pageParams.pageNo++
  } else {
    finish.value = true
  }
}
// 下拉刷新函数
const refreshRentHousePageList = async () => {
  const res = await getRentHousePageAPI({
    pageNo: 1,
    pageSize: 5,
    name:pageParams.name
  })
  list.value = res.data.list
  pageParams.pageNo = 1
  isTriggered.value = false
}
// 滚动触底 加载更多
const onScrolltolower = () => {
  console.log('到底了')
  getRentHousePageList()
}


// 搜索按钮
const searchBtn =async ()=>{
  const res = await getRentHousePageAPI({
    pageNo:1,
    pageSize:100,
    name:pageParams.name
  });
  list.value = res.data.list;
}
//uniapp微信小程序分享页面到微信好友
onShareAppMessage(() => {})
//uniapp微信小程序分享页面到微信朋友圈

onShareTimeline(() => {})
onLoad(() => {
  menu.value = uni.getMenuButtonBoundingClientRect()
  updateIsAccessTokenSet()
  getRentHouseList()
  getRentHousePageList()
  // getRentHouseCollectionPageList();
})

// ----------------------- 登录获取手机号方法 参数：1.code 2.encryptedData 3.iv
// 检查 accessToken 是否存在
const isAccessTokenSet = ref(!!uni.getStorageSync('accessToken'))
const updateIsAccessTokenSet = () => {
  isAccessTokenSet.value = !!uni.getStorageSync('accessToken')
  console.log('BBBB', isAccessTokenSet.value)
}

//-------------------token过期---------------------------------------------------------------------------------
const time = ref()
function myFunction() {
  time.value = uni.getStorageSync('expiresTime')||0
  // 获取当前系统时间的时间戳
  const currentTimeTimestamp = Date.now()
  // 检查Token是否过期
  if (time.value === 0) {
  } else if (currentTimeTimestamp >= time.value) {
    uni.showToast({
      title: '登录过期，请重新登录！',
      icon: 'none',
      duration: 2000,
      mask: true,
      success: function () {
        // 清理存储
        uni.removeStorageSync('accessToken')
        uni.removeStorageSync('appIdKey')
        uni.removeStorageSync('expiresTime')
      },
    })
  } else {
  }
}
const intervalId = setInterval(myFunction, 1000)
//-------------------------------------------------------------------------------------
const scene = ref()
const onGetphonenumber: UniHelper.ButtonOnGetphonenumber = async (ev) => {
  const encryptedData = ev.detail.encryptedData
    scene.value = uni.getStorageSync('scene')
  const iv = ev.detail.iv
  const res = await getSocialLoginAPI({
    code: ev.detail.code,
    encryptedData: encryptedData,    
    iv: iv,
    sourceUserId:scene.value
  })
  console.log(res)
  const bearer = 'Bearer '
  uni.setStorageSync('appIdKey', res.data.userId)
  uni.setStorageSync('accessToken', bearer + res.data.accessToken)
  uni.setStorageSync('expiresTime', res.data.expiresTime)
  updateIsAccessTokenSet()
  const detail = detailId.value
  uni.navigateTo({
    url: `/pages/simplePage/rentHouseDetail?id=${detail}`, // 假设detail页面需要id参数
  })
}
</script>
<style lang="scss">
.tagContent {
  height: 20rpx;
  left: 0;
  top: 100rpx;
  position: absolute;
}
.priceContent {
  height: 20rpx;
  left: 0;
  top: 60rpx;
  position: absolute;
}

.positionContent {
  height: 20rpx;
  left: 0;
  top: 50rpx;
  position: absolute;
  font-size: 20rpx;
}
.description {
  height: 200rpx;
  position: relative;
}
.bg {
  background: #ffffff;
  height: auto;
  width: 750rpx;
  padding: 0 27rpx;
}
.moreType {
  height: auto;

  .moreType-title {
    font-family: PingFang SC;
    font-weight: 550;
    font-size: 30rpx;
    color: #000000;
    margin-top: 49rpx;
  }

  .moreTypeConten {
    display: flex;
    // justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    width: 100%;
    height: auto;
    margin-bottom: 50rpx;

    .contentTag {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 22%;
      height: 65rpx;
      margin-top: 20rpx;
      margin-right: 17rpx;
      background: #fafafa;
      border-radius: 10rpx;
      font-family: PingFang SC;
      font-weight: 400;
      font-size: 22rpx;
      color: #000000;
    }

    /* 选择每一行的第四个元素，去除右边距 */
    contentTag:nth-child(4n) {
      margin-right: 0;
    }
  }
}
.bottom-container {
  display: flex;
  align-items: center;
  width: 750rpx;
  height: 105rpx;
  background: #ffffff;
  border-top: 1px solid #eeeeee;

  .left-reset {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    width: 50rpx;
    margin-right: 36rpx;

    .resetImg {
      width: 32rpx;
      height: 40rpx;
    }

    .resetText {
      font-family: PingFang SC;
      font-weight: 400;
      font-size: 22rpx;
      color: #000000;
    }
  }

  .confirm {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 601rpx;
    height: 70rpx;
    background: #3bc48c;
    border-radius: 35rpx;

    font-family: PingFang SC;
    font-weight: 500;
    font-size: 30rpx;
    color: #ffffff;
  }
}
page {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
.navbar {
  padding-left: 28rpx;
  padding-right: 37rpx;
  margin-top: 8rpx;
  background-color: #fff;
  background-size: cover;
  display: flex;
  align-items: center;
  .goBack {
    width: 18rpx;
    height: 30rpx;
    margin-top: 7rpx;
    margin-left: 28rpx;
  }

  .title {
    margin: 0 auto;
    font-family: PingFang SC;
    font-weight: 600;
    font-size: 36rpx;
    color: #000000;
  }
}

.search {
  display: flex;
  align-items: center;
  width: 695rpx;
  height: 70rpx;
  background: #f3f5fa;
  border-radius: 35rpx;
  margin-top: 37rpx;
  margin-left: 27rpx;

  .searchImg {
    width: 28rpx;
    height: 28rpx;
    margin-left: 25rpx;
    margin-right: 8rpx;
  }

  .input {
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 26rpx;
  }
}

.screen {
  display: flex;
  width: 100%;
  margin-top: 43rpx;
  margin-bottom: 34rpx;

  .screenItem {
    width: 25%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.screen-text {
  font-family: PingFang SC;
  font-weight: 550;
  font-size: 26rpx;
  color: #000000;
}

.market {
  width: 10rpx;
  height: 6rpx;
  margin-left: 6rpx;
}

.content {
  display: flex;
  width: 750rpx;
  height: auto;
  background-color: #f4f5fc;

  .contentItem {
    flex: 1;
    display: flex;
    align-items: center;
    width: 695rpx;
    height: 230rpx;
    background: #ffffff;
    border-radius: 20rpx;
    margin-left: 27rpx;
    margin-right: 27rpx;
    margin-top: 24rpx;

    .contentItemImg {
      width: 210rpx;
      height: 155rpx;
      background: #000000;
      border-radius: 5rpx;
      margin-left: 26rpx;
      margin-right: 21rpx;
    }
  }
}

.desTitle {
  width: 410rpx;
  font-family: PingFang SC;
  font-weight: 550;
  font-size: 30rpx;
  color: #000000;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}

.allPrice {
  font-family: PingFang SC;
  font-weight: 600;
  font-size: 30rpx;
  color: #e75841;
  margin-right: 14rpx;
}

.avgPrice {
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 22rpx;
  color: #989b9e;
}

.houseTag {
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 20rpx;
  color: #020609;
  margin-right: 20rpx;
}

.houseLabel {
  width: auto;
  height: 31rpx;
  background: #f3f4fa;
  border-radius: 3rpx;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 20rpx;
  color: #687a8c;
  padding: 6rpx 11rpx;
  margin-right: 9rpx;
}
</style>
